package com.ebelter.btcomlib.models.bluetooth.products.bracelet;


import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;

import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.bluetooth.base.BaseManager;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.bean.SendMessage;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IDataReadWriteCallback;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.interfaces.BraceletMesureResult;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.utils.BytesUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.SpUtil;
import com.ebelter.btcomlib.utils.ThreadManager;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.raizlabs.android.dbflow.sql.language.Select;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 手环
 */

public class BraceletManager extends BaseManager {

    public static final String TAG = "BraceletManager";

    public String version;//连接着的手环版本号

    private List<SendMessage> sysHistoryDate = new ArrayList<>();


    public boolean isSysingHisDataFinish;//是否已经完成同步历史数据

    //public boolean isOpenRealTimeRate;//是否有打开实时监测心率的标志


    public BraceletBytesAnalysis mBraceletBytesAnalysis;
    private BraceletBytesMake mBraceletBytesMake;


    private IShHHis mIShHHis = new IShHHis() {
        @Override
        public void sysTimeFinish(String time) {
            sysFinishTime(time);
        }

        @Override
        public void sysTimeDataError() {
            LogUtils.i(TAG,"---------------同步历史数据出错 进入了sysingHisDataFinish（）");
            sysingHisDataFinish();
        }
    };


    public BraceletManager(Context mContext) {
        super(mContext, ProductStyle.BRACELET, BraceletConstant.Bracelet_SERVICE_UUID,
                new String[]{BraceletConstant.Bracelet_WRITE_UUID},
                new String[]{BraceletConstant.Bracelet_READ_UUID1},
                true,
                100);


        mBraceletBytesAnalysis = new BraceletBytesAnalysis(mContext);
        mBraceletBytesAnalysis.setmIShHHis(mIShHHis);
        mBraceletBytesAnalysis.setBraceletManager(this);

        mBraceletBytesMake = new BraceletBytesMake();

        mServiceGatt.setIDataReadWriteCallback(new IDataReadWriteCallback() {
            @Override
            public void onCharacteristicChanged(byte[] data) {
               // LogUtils.i(TAG, "BpmManager--IDataReadWriteCallback-onCharacteristicChanged--读到-" + BytesUtils.bytes2HexStr(data));
                if (mBraceletBytesAnalysis != null) mBraceletBytesAnalysis.resultAnalysis(data);
            }

            @Override
            public void writeData(byte[] data) {
                // LogUtils.i(TAG,"ScaleBlue--IDataReadWriteCallback-writeData--写入-"+ Arrays.toString(data));
            }
        });

        deleteOneWeekAgoData();//删除手环前8天前的数据库数据

    }

    //删除7天前的历史数据
    private void deleteOneWeekAgoData() {

        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                long cT = System.currentTimeMillis();
                String yesterday = TimeUtils.formatTime14(cT - 7 * 24 * 3600000);//yyMMdd
                long yesterDaystartStr = Long.parseLong(yesterday + "0000");

                List<BraDb> dbList = new Select().from(BraDb.class)
                        .where(BraDb_Table.timeStr.lessThanOrEq(yesterDaystartStr))
                        .orderBy(BraDb_Table.timeStr, true).queryList();

                if (dbList.size() > 0) {
                    for (BraDb braDb : dbList) {
                        if (braDb != null) braDb.delete();
                    }
                }

            }
        });


    }

    //同步完某个时间点的数据
    private void sysFinishTime(String time) {
        LogUtils.i(TAG, time + "--时间点的历史数据同步完成 sysHistoryDate.size()=" + sysHistoryDate.size() + "----time = " + time);
        if (time.contains("#")) {//当前时间手环没有有效数据
            LogUtils.i(TAG, "------------------------------------------------------当前时间手环--没有--有效数据 time = " + time);
            //#18120600
            String sysTime = time.replace("#", "");//#18120600---18120600
            String todayTime = TimeUtils.formatTime17(System.currentTimeMillis());//获取到哪一天没有数据
            if (TextUtils.equals(sysTime, todayTime)) {
                //说明今天手环都没有有效数据了
                LogUtils.i(TAG, "------------------------------------------------------说明今天手环都没有有效数据了 准备结束了");
                sysingHisDataFinish();
            } else {
                //有效数据的不是今天 把下一天的时间下发下去

                String nextDayStr = TimeUtils.formatTime17(TimeUtils.parseFormatter17Time(sysTime).getTime() + 24 * 3600000);
                nextDayStr = nextDayStr.substring(0, nextDayStr.length() - 2) + "00";
                LogUtils.i(TAG, "------------------------------------------------------有效数据的不是今天 准备把下一天的时间下发下去 nextDayStr = " + nextDayStr);
                int index = -1;
                for (int i = 0; i < sysHistoryDate.size(); i++) {
                    if (sysHistoryDate.get(i).desc.contains(nextDayStr)) {
                        index = i;
                        break;
                    }
                }
                LogUtils.i(TAG, "index = " + index);
                if (index != -1 && sysHistoryDate.size() > 0 && index < sysHistoryDate.size() - 1) {
                    LogUtils.i(TAG, "-------------------for循环找到正常下发时间时间--时间是 = " + sysHistoryDate.get(index));

                    addSendMsg(sysHistoryDate.get(index));//下发时间的意思
                } else {
                    LogUtils.i(TAG, "-------------------for循环没有找到---准备结束");
                    sysingHisDataFinish();
                }
            }
            return;
        }


        int index = -1;
        for (int i = 0; i < sysHistoryDate.size(); i++) {
            if (sysHistoryDate.get(i).desc.contains(time)) {
                index = i;
                break;
            }
        }
        if (index != -1 && sysHistoryDate.size() > 0 && index < sysHistoryDate.size() - 1) {
            index++;
            addSendMsg(sysHistoryDate.get(index));//下发下一个时间的意思
        }

        if (sysHistoryDate.size() > 0 && sysHistoryDate.get(sysHistoryDate.size() - 1).desc.contains(time)) {

            sysingHisDataFinish();
        }


    }


    private void sysingHisDataFinish() {
        isSysingHisDataFinish = true;
        LogUtils.i(TAG, "历史数据全部同步完成");


        int xlCycmin = UserSpUtil.readInt(Constants.IUser.SHH_XL_TIME, 10);//设置手环心率周期
        setHeartCycle(xlCycmin);

        CommonEventBus commonEventBus = new CommonEventBus(BraceletManager.TAG, "MainActivity", 2, "关闭同步历史数据框");
        EventBus.getDefault().post(commonEventBus);


        // queryOneDayDate();//查询今天的数据

        if (mBraceletMesureResult != null) mBraceletMesureResult.sysHistoryDataFinish();

    }


    BraceletMesureResult mBraceletMesureResult;

    public void setmBraceletMesureResult(BraceletMesureResult mBraceletMesureResult) {
        this.mBraceletMesureResult = mBraceletMesureResult;
        mBraceletBytesAnalysis.setBraceletMeasureCallback(mBraceletMesureResult);
    }


    public boolean isBondDevice() {
        String add = getBondDeviceAddress();
        return !TextUtils.isEmpty(add);
    }

    public String getBondDeviceAddress() {
        return SpUtil.readString(BraceletConstant.Bracelet_BOND_DEVICE_ADDRESS, null);
    }

    public void setBondDeviceAddress(String address) {
        SpUtil.writeString(BraceletConstant.Bracelet_BOND_DEVICE_ADDRESS, address);
    }


    //同步设备时间
    public void sysDeviceTime() {
        addSendMsg(mBraceletBytesMake.sysTime());
      //  getVersion();//获取一下固件版本号
    }





    //设置用户信息 160cm
    // 52kg
    // sex 0为女1为男
    public void setUserInfo(int height, int weight, int sex) {
        addSendMsg(mBraceletBytesMake.setUserInfo(height, weight, sex));
    }



    //关闭消息通知
    public void closeNotifications() {
        addSendMsg(mBraceletBytesMake.getCloseNotification());
    }
    /**
     * 设置抬腕亮屏
     *
     * @param isOpen true: 开启  false:  关闭
     */
    public void setUPHandGesture(boolean isOpen) {
        addSendMsg(mBraceletBytesMake.setUPHandGesture(isOpen));
    }

    //设置测量心率周期
    public void setHeartCycle(int min) {
        if (isConnect()) {
            addSendMsg(mBraceletBytesMake.setHeartCycle(min));
        }
    }


    //获取实时数据
    public void getLiveData() {
        addSendMsg(mBraceletBytesMake.getLiveData());
    }


    public void getVersion(){addSendMsg(mBraceletBytesMake.getVersionData());}

    //打开或者关闭实时心率
    public void getHeartRate(boolean isOpen) {
        addSendMsg(mBraceletBytesMake.getHeartRate(isOpen));
    }


    //开始同步历史数据
    public void sysHistoryData2(final String newestTimeStr){
      ThreadManager.getShortPool().execute(new Runnable() {
          @Override
          public void run() {
              sysHistoryDate.clear();

              //  newestTimeStr = "2019-01-10 15:53:34";
              List<String> times = new ArrayList<>();

              LogUtils.i(TAG,"心跳最新时间 服务器上的 newestTimeStr = "+newestTimeStr);
              long currentTime = System.currentTimeMillis();//当前时间HH:mm:ss
              long tianqian_6Time =  TimeUtils.parseFormatter1Time(TimeUtils.formatTime3(currentTime-6*86400000)+" 00:00:00").getTime();//7天前的开始时间
              long tianqian_1Time =  TimeUtils.parseFormatter1Time(TimeUtils.formatTime3(currentTime-1*86400000)+" 00:00:00").getTime();//2天前的开始时间
              long tianqian_0Time =  TimeUtils.parseFormatter1Time(TimeUtils.formatTime3(currentTime)+" 00:00:00").getTime();//今天前的开始时间


              long newestTimeLong;
              //当时间格式不正确的时候就用7天前的0点开始 否则按照时间上的来
              if (!TextUtils.isEmpty(newestTimeStr)&&TimeUtils.judgingTimeFormat(newestTimeStr,"yyyy-MM-dd HH:mm:ss")){

                  long newestTimeLong2 = TimeUtils.parseFormatter1Time(newestTimeStr).getTime();//计算出传进来的时间long
                  newestTimeLong = TimeUtils.parseFormatter37Time(TimeUtils.formatTime17(newestTimeLong2)+"0000").getTime();//yyMMddHH--->yyMMddHHmmss

                  //上面是计算出心跳最新的时间 判断这个时间是否在这7天以内
                  if (newestTimeLong>tianqian_6Time&&newestTimeLong<currentTime){
                      LogUtils.i(TAG,"心跳最新时间 newestTimeStr ---是---在currentTime和tianqian_6Time的值 ---时间是准确的");
                  }else {
                      LogUtils.i(TAG,"心跳最新时间 newestTimeStr ---不是---在currentTime和tianqian_6Time的值 ---时间是不准确的 时间采用了7天前的时间");
                      newestTimeLong = tianqian_6Time;
                  }
              }else {
                  newestTimeLong = tianqian_6Time;//如果传进来的时间不符合要求就直接同步最长时间的
              }

             //为了本地中能够显示今天和昨天的展示数据 必须查一遍数据库里面最新的一条数据是什么时候
              List<BraDb> braDbLists = new Select().from(BraDb.class).where().orderBy(BraDb_Table.timeStr, true).queryList();

              Long dbNewestTime;

              if (CommonLib.isDebug){//这里的意思是可打可不打的意思 如果发现app运行速度降低了 就把CommonLib.isDebug置为false
                  int i = 0;
                  for (BraDb braDb :braDbLists) {
                      i++;
                      LogUtils.i(TAG, "数据库-------i = " + i + "----" + braDb.toString());
                  }
              }

              BraDb dbNewestBraDb;//取到数据库里面最后一条数据
              if (braDbLists.size() > 0) {//说明本地数据库有数据
                  dbNewestBraDb = braDbLists.get(braDbLists.size() - 1);//1809112050
                  dbNewestTime = TimeUtils.parseFormatter15Time(dbNewestBraDb.timeStr+"").getTime();//yyMMddHHmm

                  LogUtils.i(TAG, "数据库最后一条数据=" + dbNewestBraDb.toString());

                  if (dbNewestTime < tianqian_6Time){//数据库里面最后一条的时间是6天以前的
                      newestTimeLong = tianqian_6Time;
                      LogUtils.i(TAG, "数据库有数据 因为最后一条时间是6天前的 同步时间采取7天前的 newestTimeLong  = " + TimeUtils.formatTime1(newestTimeLong));
                  }else{
                      if (dbNewestTime < newestTimeLong){
                          newestTimeLong = dbNewestTime;
                          LogUtils.i(TAG, "数据库有数据 因为最后一条时间小于了即将同步的时间点 故 newestTimeLong  = " + TimeUtils.formatTime1(newestTimeLong));
                      }
                  }

              }else {//说明本地数据库没有数据
                  LogUtils.i(TAG, "数据库没有数据A");
                  if (newestTimeLong > tianqian_1Time){
                      newestTimeLong = tianqian_1Time;
                      LogUtils.i(TAG, "数据库没有数据A1 同步时间采取 1天前0点0分的  = " + TimeUtils.formatTime1(newestTimeLong));
                  }else {
                      LogUtils.i(TAG, "数据库没有数据A2 同步时间采取 newestTimeLong  = " + TimeUtils.formatTime1(newestTimeLong));
                  }
              }

              if (newestTimeLong > tianqian_0Time){
                  newestTimeLong = tianqian_0Time;
                  LogUtils.i(TAG, "时间纠正 同步时间点大于今天的时间点 同步时间采取 今天0点0分的  = " + TimeUtils.formatTime1(newestTimeLong));
              }

              LogUtils.i(TAG,"当前时间 currentTime = "+TimeUtils.formatTime1(currentTime)+" ---6天前的tianqian_6Time = "+TimeUtils.formatTime1(tianqian_6Time));

              String  newestTimeStr = TimeUtils.formatTime1(newestTimeLong);
              LogUtils.i(TAG,"心跳最新最终结果同步采取的时间是 newestTimeLong = "+newestTimeStr);

              UserSpUtil.writeLong(BraceletConstant.B_NEWEST_HEART_TIME_L,newestTimeLong);//记录一下最新的同步时间
              UserSpUtil.writeString(BraceletConstant.B_NEWEST_HEART_TIME_STR,newestTimeStr);


              long newestTimeLong2 = newestTimeLong;
              while (newestTimeLong2<currentTime){
                  String time = TimeUtils.formatTime17(newestTimeLong2);
                  times.add(time);
                  newestTimeLong2+=3600000;//3600000是一个小时的毫秒数
              }

              LogUtils.i(TAG, "加入的时间集合"+times.toString());


              //拿到数据库的数据
           //   List<BraDb> braDbList = new Select().from(BraDb.class).where().orderBy(BraDb_Table.timeStr, true).queryList();
//              BraDb newestBraDb;
//              Long newestTime = 0L;
//              for (int i = 0; i < braDbList.size(); i++) {
//                  LogUtils.i(TAG, "数据库-------i = " + i + "----" + braDbList.get(i).toString());
//              }
//              if (braDbLists.size() > 0) {
//                  newestBraDb = braDbLists.get(braDbLists.size() - 1);//1809112050
//                  newestTime = newestBraDb.timeStr / 100;
//              }

              for (String time : times) {
                 // long ct = NumUtils.string2Long(time);//time 19011005
                  //if (ct >= newestTime) {
                      byte[] cmd = new byte[20];
                      cmd[0] = 0x02;
                      cmd[1] = 0x08;
                      cmd[2] = (byte) Integer.parseInt(time.substring(0, 2));
                      cmd[3] = (byte) Integer.parseInt(time.substring(2, 4));
                      cmd[4] = (byte) Integer.parseInt(time.substring(4, 6));
                      cmd[5] = (byte) Integer.parseInt(time.substring(6, 8));
                      for (int i = 6; i < 20; i++) {
                          cmd[i] = 0;
                      }
                      SendMessage msg = new SendMessage();
                      msg.desc = "同步历史数据time=" + time;
                      msg.datas = cmd;
                      LogUtils.i(TAG, "同步历史数据 时间加入集合 time="+ time + BytesUtils.bytes2HexStr(cmd));
                      sysHistoryDate.add(msg);
                  //}
              }

             // LogUtils.i(TAG, "同步数据 发送时间的指令集合 sysHistoryDate = "+ sysHistoryDate.toString());
              if (sysHistoryDate.size() > 0&&isConnect()) {//开始同步的意思
                  LogUtils.i(TAG, "--------------------同步历史数据 集合大于零 开始同步历史数据 ");
                  isSysingHisDataFinish = false;

                  CommonEventBus commonEventBus = new CommonEventBus(BraceletManager.TAG, "MainActivity", 1, "展示同步历史数据框");
                  EventBus.getDefault().post(commonEventBus);

                  addSendMsg(sysHistoryDate.get(0));//开始同步第一个
              }
          }
      });
    }




    //同步历史数据
    public void sysHistoryData(final int tianshu) {


        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {


                sysHistoryDate.clear();

                long currentTime = System.currentTimeMillis();
                String currentTimeStr = TimeUtils.formatTime14(currentTime);//yyMMdd 解析当前时间

                List<String> dates = new ArrayList<>();
                Date date = new Date();
                for (int i = tianshu; i > 0; i--) {
                    long temp = currentTime - (i - 1) * 24 * 3600 * 1000;
                    String tempTimeStr = TimeUtils.formatTime14(temp);//yyMMdd
                    if (!TextUtils.equals(currentTimeStr, tempTimeStr)) {
                        for (int j = 0; j < 24; j++) {
                            String h;
                            if (j < 10) {
                                h = "0" + j;
                            } else {
                                h = j + "";
                            }
                            dates.add(tempTimeStr + h);
                        }
                    } else {
                        //今天
                        for (int j2 = 0; j2 < date.getHours() + 1; j2++) {
                            String h;
                            if (j2 < 10) {
                                h = "0" + j2;
                            } else {
                                h = j2 + "";
                            }
                            dates.add(tempTimeStr + h);
                        }
                    }
                }


                //最长两天的数据
                List<BraDb> braDbList = new Select().from(BraDb.class).where().orderBy(BraDb_Table.timeStr, true).queryList();


                BraDb newestBraDb;
                Long newestTime = 0l;
                for (int i = 0; i < braDbList.size(); i++) {
                    LogUtils.i(TAG, "数据库-------i = " + i + "----" + braDbList.get(i).toString());
                }
                if (braDbList.size() > 0) {
                    newestBraDb = braDbList.get(braDbList.size() - 1);//1809112050
                    newestTime = newestBraDb.timeStr / 100;
                }


                LogUtils.i(TAG, "加入的时间集合"+dates.toString());

                for (String time : dates) {
                    long ct = NumUtils.string2Long(time);//time 19011005

                    if (ct >= newestTime) {
                        byte[] cmd = new byte[20];
                        cmd[0] = 0x02;
                        cmd[1] = 0x08;
                        cmd[2] = (byte) Integer.parseInt(time.substring(0, 2));
                        cmd[3] = (byte) Integer.parseInt(time.substring(2, 4));
                        cmd[4] = (byte) Integer.parseInt(time.substring(4, 6));
                        cmd[5] = (byte) Integer.parseInt(time.substring(6, 8));
                        for (int i = 6; i < 20; i++) {
                            cmd[i] = 0;
                        }
                        SendMessage msg = new SendMessage();
                        msg.desc = "同步历史数据time=" + time;
                        msg.datas = cmd;
                        LogUtils.i(TAG, "同步历史数据 时间加入集合 time="+ time +BytesUtils.bytes2HexStr(cmd));
                        sysHistoryDate.add(msg);
                    }


                }

                if (sysHistoryDate.size() > 0) {//开始同步的意思

                    LogUtils.i(TAG, "--------------------同步历史数据 集合大于零 开始同步历史数据 ");
                    isSysingHisDataFinish = false;

                    CommonEventBus commonEventBus = new CommonEventBus(BraceletManager.TAG, "MainActivity", 1, "展示同步历史数据框");
                    EventBus.getDefault().post(commonEventBus);

                    removeMessages(what_CancelSysDialog);
                    sendEmptyMessageDelayed(what_CancelSysDialog, 45000);//45秒后消失同步框的意思

                    addSendMsg(sysHistoryDate.get(0));//开始同步第一个
                }

            }
        });


    }

    private static final int what_CancelSysDialog = 99;

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        if (msg.what == what_CancelSysDialog) {
            CommonEventBus commonEventBus = new CommonEventBus(BraceletManager.TAG, "MainActivity", 2, "强制关闭同步历史数据框");
            EventBus.getDefault().post(commonEventBus);
        }
    }

    public void setConnectDevice(BluetoothDevice device) {
        if (mBraceletBytesAnalysis!=null)mBraceletBytesAnalysis.connectAddress(device.getAddress());
    }
//
    public void sendOtaUpdate() {
        addSendMsg(mBraceletBytesMake.getOtaUpdateCmd());
    }

    interface IShHHis {
        void sysTimeFinish(String time);
        void sysTimeDataError();

    }

}
